package com.dxd.onlineshop.controller;

import com.dxd.onlineshop.pojo.Address;
import com.dxd.onlineshop.service.AddressService;
import com.dxd.onlineshop.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/addresses")
public class AddressController {

    private final AddressService addressService;

    @Autowired
    public AddressController(AddressService addressService) {
        this.addressService = addressService;
    }

    // 获取用户的所有地址
    @GetMapping
    public ResponseEntity<?> getUserAddresses(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromToken(request);
            List<Address> addresses = addressService.getUserAddresses(userId);
            return ResponseEntity.ok(addresses);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的token");
        }
    }

    // 获取单个地址详情
    @GetMapping("/{id}")
    public ResponseEntity<?> getAddress(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromToken(request);
            Address address = addressService.getAddress(id);
            if (address != null && address.getUserId().equals(userId)) {
                return ResponseEntity.ok(address);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的token");
        }
    }

    // 添加新地址
    @PostMapping
    public ResponseEntity<?> addAddress(@RequestBody Address address, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromToken(request);
            address.setUserId(userId);
            addressService.addAddress(address);
            return ResponseEntity.status(HttpStatus.CREATED).body("地址添加成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 更新现有地址
    @PutMapping("/{id}")
    public ResponseEntity<?> updateAddress(@PathVariable Long id, @RequestBody Address address, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromToken(request);
            address.setId(id);
            addressService.updateAddress(userId, address);
            return ResponseEntity.ok("地址更新成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 删除地址
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAddress(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromToken(request);
            addressService.deleteAddress(userId, id);
            return ResponseEntity.ok("地址删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 设置默认地址
    @PutMapping("/{id}/default")
    public ResponseEntity<?> setDefaultAddress(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromToken(request);
            System.out.println(id);
            addressService.setDefaultAddress(userId, id);
            return ResponseEntity.ok("默认地址设置成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 获取用户地址数量
    @GetMapping("/count")
    public ResponseEntity<?> getAddressCount(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromToken(request);
            int count = addressService.getAddressCount(userId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的token");
        }
    }

    // 从token中获取用户ID的辅助方法
    private Long getUserIdFromToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        Map<String, Object> claims = JwtUtil.parseToken(token);
        Integer userId = (Integer) claims.get("userId");
        return Long.valueOf(userId);
    }
}